const mysql = require('mysql2/promise');
const config = require('./database-config.js');

async function manualCompleteTraining() {
  const connection = await mysql.createConnection(config.source);
  
  console.log('🏋️ 手动完成训练并测试升级逻辑...');
  
  try {
    await connection.beginTransaction();
    
    // 获取训练记录
    const [trainings] = await connection.execute('SELECT * FROM character_training WHERE character_id = 2007 AND is_training = 1');
    if (trainings.length === 0) {
      console.log('❌ 没有找到正在进行的训练');
      return;
    }
    
    const training = trainings[0];
    console.log(`📋 找到训练记录: ID=${training.id}, 训练小时=${training.training_hours}`);
    
    // 获取角色信息
    const [characters] = await connection.execute('SELECT * FROM characters WHERE id = 2007');
    if (characters.length === 0) {
      console.log('❌ 角色不存在');
      return;
    }
    
    const character = characters[0];
    console.log(`👤 角色信息: 等级=${character.lvl}, 经验=${character.exp}`);
    
    // 计算获得的经验值
    const level = character.lvl;
    const multiplier = 1; // 简化计算
    const baseExp = 100; // 基础经验值
    const expGained = baseExp * multiplier * training.training_hours;
    
    console.log(`📊 计算经验: 基础经验=${baseExp}, 倍数=${multiplier}, 训练小时=${training.training_hours}, 获得经验=${expGained}`);
    
    // 更新角色经验（exp字段代表升级还需要多少经验，训练应该减少这个值）
    let newExp = character.exp - expGained;
    let newLevel = character.lvl;
    let leveledUp = false;
    
    console.log(`🔄 经验计算: 当前经验=${character.exp}, 获得经验=${expGained}, 新经验=${newExp}`);
    
    // 检查是否升级
    if (newExp <= 0) {
      leveledUp = true;
      newLevel = character.lvl + 1;
      // 计算下一级所需经验（这里使用简单的公式，可以根据需要调整）
      newExp = newLevel * 1000; // 下一级所需经验
      console.log(`🎉 角色升级！从等级${character.lvl}升级到等级${newLevel}，下一级需要${newExp}经验`);
    }
    
    // 更新角色
    await connection.execute('UPDATE characters SET exp = ?, lvl = ? WHERE id = 2007', [newExp, newLevel]);
    console.log(`✅ 角色更新: 等级=${newLevel}, 经验=${newExp}`);
    
    // 更新训练记录
    await connection.execute('UPDATE character_training SET is_training = 0, training_status = 2, training_start_time = NULL, training_end_time = NULL, training_hours = 0 WHERE id = ?', [training.id]);
    console.log('✅ 训练记录已更新');
    
    await connection.commit();
    
    // 验证结果
    const [updatedCharacters] = await connection.execute('SELECT id, name, lvl, exp FROM characters WHERE id = 2007');
    console.log('📊 最终结果:');
    updatedCharacters.forEach(char => {
      console.log(`  - ${char.name} (ID: ${char.id}): 等级=${char.lvl}, 经验=${char.exp}`);
    });
    
  } catch (error) {
    await connection.rollback();
    console.error('❌ 操作失败:', error.message);
  } finally {
    await connection.end();
  }
}

manualCompleteTraining();
